#!/usr/bin/env python3
"""
生产环境Docker部署示例
演示如何在生产环境中使用Docker部署统一日志模块
"""

import os
import asyncio
from unified_logger import AsyncUnifiedLogger, LogLevel


async def production_logging_demo():
    """生产环境日志演示"""
    
    # 从环境变量读取配置
    log_level = os.getenv('LOG_LEVEL', 'INFO')
    log_file = os.getenv('LOG_FILE', '/app/logs/app.log')
    max_file_size = int(os.getenv('LOG_MAX_FILE_SIZE', '10485760'))  # 10MB
    backup_count = int(os.getenv('LOG_BACKUP_COUNT', '5'))
    
    # 创建生产环境日志器
    logger = AsyncUnifiedLogger(
        name="production_app",
        log_level=getattr(LogLevel, log_level.upper()),
        enable_console=True,
        enable_file=True,
        log_file=log_file,
        max_file_size=max_file_size,
        backup_count=backup_count,
        enable_json_format=True  # 生产环境使用JSON格式
    )
    
    try:
        await logger.start()
        
        # 记录应用启动信息
        await logger.info(
            "应用启动",
            extra={
                "event": "application_start",
                "version": "1.0.0",
                "environment": os.getenv('ENVIRONMENT', 'production'),
                "hostname": os.getenv('HOSTNAME', 'unknown'),
                "port": int(os.getenv('PORT', 8080))
            }
        )
        
        # 模拟生产环境操作
        await simulate_production_work(logger)
        
        # 记录应用关闭信息
        await logger.info(
            "应用关闭",
            extra={
                "event": "application_shutdown",
                "uptime_seconds": 3600,
                "total_requests": 1250,
                "error_rate": 0.02
            }
        )
        
    finally:
        await logger.stop()


async def simulate_production_work(logger):
    """模拟生产环境工作负载"""
    
    # 模拟用户请求
    for i in range(100):
        # 模拟API请求
        request_id = f"req-{i:06d}"
        
        await logger.info(
            "处理用户请求",
            extra={
                "request_id": request_id,
                "user_id": 1000 + i,
                "endpoint": "/api/v1/data",
                "method": "POST",
                "payload_size": 1024
            }
        )
        
        # 模拟数据处理
        await asyncio.sleep(0.01)
        
        # 记录处理结果
        if i % 10 == 0:  # 10%的错误率
            await logger.error(
                "请求处理失败",
                extra={
                    "request_id": request_id,
                    "error_code": "VALIDATION_ERROR",
                    "error_message": "Invalid input data format",
                    "retry_count": 3
                }
            )
        else:
            await logger.info(
                "请求处理成功",
                extra={
                    "request_id": request_id,
                    "response_time_ms": 45.2,
                    "response_size": 2048,
                    "status_code": 200
                }
            )
        
        # 每20个请求记录一次性能指标
        if i % 20 == 0:
            await logger.info(
                "性能指标",
                extra={
                    "metric_type": "performance_snapshot",
                    "memory_usage_mb": 256.5,
                    "cpu_percent": 35.2,
                    "active_connections": 150,
                    "queue_size": 25,
                    "error_count": i // 10
                }
            )


if __name__ == "__main__":
    print("生产环境Docker部署示例")
    print("运行环境变量：")
    print("- LOG_LEVEL=INFO")
    print("- LOG_FILE=/app/logs/app.log")
    print("- LOG_MAX_FILE_SIZE=10485760")
    print("- LOG_BACKUP_COUNT=5")
    print("- ENVIRONMENT=production")
    
    asyncio.run(production_logging_demo())